﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Security;

namespace DNA.Mvc
{
    public class ReceivePasswordEventObserver : TemplatedMailEventObserver<ReceivePasswordEvent>
    {
        private readonly Regex UsernameRegex = new Regex("\\{username\\}", RegexOptions.Compiled);
        private readonly Regex ValidationRegex = new Regex("\\{validationUrl\\}", RegexOptions.Compiled);
        private string token = "";
        private string validationUrl = "";
        private string subject = "Password change validation";
        private string username = "";

        /// <summary>
        /// Get/Sets the email subject
        /// </summary>
        public override string Subject
        {
            get { return subject; }
            set { subject = value; }
        }

        protected override string GetDestinationAddress(ReceivePasswordEvent e)
        {
            return e.Email;
        }

        protected override void OnFormatHtmlBody(ReceivePasswordEvent e, ref string html)
        {
            html = UsernameRegex.Replace(html, username);
            html = ValidationRegex.Replace(html, validationUrl);
        }

        protected override void OnFormatTextBody(ReceivePasswordEvent e, ref string text)
        {
            var bodyText = new StringBuilder();
            bodyText.Append("Hi:")
                .AppendLine(username)
                .AppendLine("You send a password receive request just now.Our security policy need to validate the request.")
                .AppendLine("If you not validate this request, it will be timeout an unvalidable at " + DateTime.UtcNow.AddMinutes(10).ToLongTimeString())
                .AppendLine("Please click the following link to validate your request:")
                .AppendLine(validationUrl);
            text = bodyText.ToString();
        }

        public override void Process(ReceivePasswordEvent e)
        {
            if (string.IsNullOrEmpty(e.Email))
                return;
            username = Membership.GetUserNameByEmail(e.Email);
            
            if (string.IsNullOrEmpty(username))
                return;

            token = (e.Email.ToLower() + DateTime.Now.ToString().ToLower()).GetHashCode().ToString();
            validationUrl = UrlResolver.Resolve(e.HttpContext) + "/Account/ValidateEmail?token=" + token;
            var cache = e.HttpContext.Cache;
            if (cache[token] != null)
                cache.Remove(token);

            cache.Add(token, e.Email, null, DateTime.Now.AddMinutes(10), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, null);

            base.Process(e);
        }
    }
}
